package com.um.springboot.starter.controller;

import cn.hutool.core.util.StrUtil;
import com.um.springboot.starter.code.CommonCode;
import com.um.springboot.starter.helper.SessionHelper;
import com.um.springboot.starter.properties.HshProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.util.*;

@Slf4j
@RestController
public class WEditorFileController {

    @Autowired
    HshProperties hshProperties;

    @Autowired
    SessionHelper sessionHelper;

    @PostMapping("/api/v1/editor/upload")
    public Map upload(MultipartHttpServletRequest request) throws IOException {

        Map returnData = new HashMap();
        if(!hshProperties.getFile().isAllowEditorUpload()){
            returnData.put("msg", CommonCode.NotOpen.getMsg()); //在此处写上错误提示信息，这样当错误的时候就会显示此信息
            returnData.put("errno", "9");
            returnData.put("data", "");
            return returnData;
        }
        if (!hshProperties.getFile().isAllowAnonymousUpload() && StrUtil.isBlank(sessionHelper.getSessionUserId())) {
            returnData.put("msg", CommonCode.LoginExpired.getMsg());
            returnData.put("errno", "9");
            returnData.put("data", "");
            return returnData;
        }

        Map<String, MultipartFile> multipartFiles = request.getFileMap();
        String uploadFilePath = "";
        try{
            if(hshProperties.getConfig().getPackaging().equals("jar") || !hshProperties.getFile().isRelative()){
                uploadFilePath = hshProperties.getFile().getPath();
            }else {
                uploadFilePath = ResourceUtils.getURL("classpath:").getPath() + "static" + hshProperties.getFile().getPath();

            }
        }catch (Exception ex){
            log.error("", ex);
        }
        uploadFilePath += "/editor";
        log.info("uploadPath:"+uploadFilePath);

        //Map returnData = new HashMap();
        List dataList = new ArrayList();
        StringBuffer url = request.getRequestURL();

        String tempContextUrl = "";//
        if(hshProperties.getFile().isRelative()) {
            tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getSession().getServletContext().getContextPath()).append("/").toString();
        }else{
            tempContextUrl = hshProperties.getFile().getDomain();
        }
        for(Map.Entry<String, MultipartFile> entry : multipartFiles.entrySet()){
            MultipartFile file = entry.getValue();
            String originFileName = file.getOriginalFilename();

            // 上传文件重命名
            String newOriginFileName = UUID.randomUUID().toString();
            newOriginFileName = newOriginFileName.concat(".");
            newOriginFileName = newOriginFileName.concat(originFileName.substring(originFileName.indexOf(".") + 1));

            if (!file.isEmpty()) {

                if (makeDir(uploadFilePath) && createFile(uploadFilePath,newOriginFileName)){

                    File dest = new File(uploadFilePath, newOriginFileName);
                    try {
                        file.transferTo(dest);
                        //文本编辑器上传返回绝对路径
                        if(hshProperties.getFile().isRelative()) {
                            dataList.add(tempContextUrl + "upload/editor/" + newOriginFileName);
                        }else{
                            dataList.add(tempContextUrl + "/editor/" + newOriginFileName);
                        }

                    } catch (IOException e) {
                        log.error("上传出错：", e);

                        returnData.put("errno",9);
                        return returnData;
                    }
                }
            }
        }

        returnData.put("errno",0);
        returnData.put("data",dataList);

        return returnData;
    }

    @PostMapping("/api/v5/editor/upload")
    public Map uploadV5(MultipartHttpServletRequest request) throws IOException {

        Map returnData = new HashMap();
        if(!hshProperties.getFile().isAllowEditorUpload()){
            returnData.put("message", CommonCode.NotOpen.getMsg());
            returnData.put("errno", "9");
            return returnData;
        }
        if (!hshProperties.getFile().isAllowAnonymousUpload() && StrUtil.isBlank(sessionHelper.getSessionUserId())) {
            returnData.put("msg", CommonCode.LoginExpired.getMsg());
            returnData.put("errno", "9");
            return returnData;
        }

        MultipartFile file = request.getFile("wangeditor-uploaded-image");
        if (null == file || file.isEmpty()) {
            file = request.getFile("wangeditor-uploaded-video");
            if (null == file || file.isEmpty()) {
                returnData.put("message", "文件不存在!");
                returnData.put("errno", "9");
                return returnData;
            }
        }

        String uploadFilePath = "";
        try{
            if(hshProperties.getConfig().getPackaging().equals("jar") || !hshProperties.getFile().isRelative()){
                uploadFilePath = hshProperties.getFile().getPath();
            }else {
                uploadFilePath = ResourceUtils.getURL("classpath:").getPath() + "static" + hshProperties.getFile().getPath();

            }
        }catch (Exception ex){
            log.error("获取文件长传路径错误", ex);
        }

        uploadFilePath += "/editor";
        log.info("uploadPath:"+uploadFilePath);


        String tempContextUrl = "";
        if(hshProperties.getFile().isRelative()) {
            StringBuffer url = request.getRequestURL();
            tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getSession().getServletContext().getContextPath()).append("/").toString();
        }else{
            tempContextUrl = hshProperties.getFile().getDomain();
        }

        // 上传文件重命名
        String originFileName = file.getOriginalFilename();
        String newOriginFileName = UUID.randomUUID().toString();
        newOriginFileName = newOriginFileName.concat(".");
        newOriginFileName = newOriginFileName.concat(originFileName.substring(originFileName.indexOf(".") + 1));


        String fileUrl = "";
        if (makeDir(uploadFilePath) && createFile(uploadFilePath,newOriginFileName)){

            File dest = new File(uploadFilePath, newOriginFileName);
            try {
                file.transferTo(dest);
                //文本编辑器上传返回绝对路径
                if(hshProperties.getFile().isRelative()) {
                    fileUrl = tempContextUrl + "upload/editor/" + newOriginFileName;
                }else{
                    fileUrl = tempContextUrl + "/editor/" + newOriginFileName;
                }

            } catch (IOException e) {
                log.error("上传出错：", e);

                returnData.put("errno",9);
                returnData.put("message", "上传文件失败!");
                return returnData;
            }
        }

        Map data = new HashMap();
        data.put("url", fileUrl);

        returnData.put("errno", 0);
        returnData.put("data", data);

        return returnData;
    }


    /**
     * 如果目录不存在，则创建目录
     * @param path 需要创建的目录
     * @return 存在或创建成功返回true
     */
    private boolean makeDir(String path)
    {
        boolean mk = true;
        File myPath = new File(path);
        if (!myPath.exists())
        {
            mk = myPath.mkdirs();
        }
        return mk;
    }

    /**
     * 如果文件不存在，则创建一个新文件
     * @param path 文件的路径
     * @param fileName 文件名称
     * @return 文件存在或创建成功返回true
     * @throws IOException
     */
    private boolean createFile(String path, String fileName)
    {
        boolean creator = true;
        File myPath = new File(path, fileName);
        if (!myPath.exists())
        {
            try{
                creator = myPath.createNewFile();
            }catch(Exception ex){
                creator = false;
                log.error("上传文件：创建文件出错:"+ex.getMessage());
            }
        }
        return creator;

    }


}
